<template>
    <d2-container>
        <!-- 搜索表头 -->
        <template slot="header">

            <el-form :inline="true" :model="configForm" ref="configForm" size="small">
                <el-form-item label="包路径" prop="package" :rules="[{ required: true, message: '包路径不能为空'}]">
                    <el-input v-model="configForm.package" clearable placeholder="请输入包路径" />
                </el-form-item>
                <el-form-item label="模块名" prop="moduleName" :rules="[{ required: false, message: '模块名不能为空'}]">
                    <el-input v-model="configForm.moduleName" clearable placeholder="请输入模块名" />
                </el-form-item>
                <el-form-item label="开发者" prop="author">
                    <el-input v-model="configForm.author" clearable placeholder="请输入开发者" />
                </el-form-item>
                <el-form-item label="邮箱" prop="email">
                    <el-input v-model="configForm.email" clearable placeholder="请输入邮箱" />
                </el-form-item>
                <el-form-item label="表前缀" prop="tablePrefix">
                    <el-input v-model="configForm.tablePrefix" clearable placeholder="请输入表前缀" />
                </el-form-item>
            </el-form>

            <div style="margin-bottom:10px">
                <el-button icon="el-icon-search" size="small" style="margin-right:10px" @click="selectTemplate()">选择模板
                </el-button>
                <!-- 模板列表:{{templateList}} -->
                <el-tag :key="tag.pkTemplate" v-for="tag in templateList" style="margin-right:10px;margin-bottom:10px"
                    closable @close="handleClose(tag)">
                    {{tag.templateName}}
                </el-tag>

            </div>
        </template>


        <!-- 表格表头 -->
        <div class="table-header">
            <div>
                <el-button type="primary" icon="el-icon-document" size="small" @click="generateCode()">生成代码
                </el-button>
                <el-button type="primary" icon="el-icon-edit-outline" size="small"
                    :disabled="multipleSelection.length > 1" @click="generateMateData()">生成元数据
                </el-button>
            </div>
            <div>
                <el-button size="small" round icon="el-icon-refresh" @click="getDataTable()"></el-button>
                <el-popover placement="top-start" title="温馨提示" width="400" trigger="hover"
                    style="display: inline-block;margin: 0 10px;">
                    <el-button slot="reference" size="small" round icon="el-icon-discover"></el-button>
                </el-popover>
                <el-button size="small" round icon="el-icon-search" @click="changeHeader()"></el-button>
            </div>
        </div>


        <el-form :inline="true" :model="searchForm" ref="searchForm" size="small" v-if="showHeader" style="padding: 0px;margin-bottom:20px">
            <!-- class="searchHeader" -->
            <el-form-item label="数据库类型" prop="dbType" :rules="[{ required: true, message: '数据库类型不能为空'}]">
                <el-select v-model="searchForm.dbType" placeholder="请输入数据库类型" clearable>
                    <el-option v-for="item in dbTypeOptions" :key="item.value" :label="item.label" :value="item.value">
                    </el-option>
                </el-select>
            </el-form-item>
            <!-- <el-form-item label="数据库名称" prop="dbName" v-if="searchForm.dbType == 'mysql'"
                :rules="[{ required: true, message: '数据库名称不能为空'}]">
                <el-select v-model="searchForm.dbName" placeholder="请输入数据库名称" clearable>
                    <el-option v-for="item in dbNameOptions" :key="item.value" :label="item.label" :value="item.value">
                    </el-option>
                </el-select>
            </el-form-item> -->
            <el-form-item label="数据库名称" prop="dbName" v-if="searchForm.dbType == 'mysql'"
                :rules="[{ required: true, trigger: 'change',  message: '数据库名称不能为空'}]">
                <el-select v-model="centerData" placeholder="请选择数据中心" @change="dataChange" value-key="pkModule">
                    <el-option v-for="item in centerDatas" :key="item.pkModule" :label="item.moduleName" :value="item">
                    </el-option>
                </el-select>
            </el-form-item>
            <el-form-item label="表名" prop="tableName">
                <el-input v-model="searchForm.tableName" clearable placeholder="请输入表名" />
            </el-form-item>

            <el-form-item>
                <el-button type="primary" @click="getDataTable">
                    <d2-icon name="search" />
                    查询
                </el-button>
                <el-button @click="handleFormReset">
                    <d2-icon name="refresh" />
                    重置
                </el-button>
            </el-form-item>
        </el-form>

        <!-- 表格表体 -->
        <ec-table :data="tabledata" v-loading="loading" @selection-change="handleSelectionChange">
            <el-table-column type="selection" header-align="center" align="center" width="50">
            </el-table-column>
            <el-table-column prop="tableName" header-align="center" align="center" show-overflow-tooltip label="表名">
            </el-table-column>
            <el-table-column prop="engine" header-align="center" align="center" show-overflow-tooltip label="存储引擎">
            </el-table-column>
            <el-table-column prop="tableComment" header-align="center" align="center" show-overflow-tooltip label="表备注">
            </el-table-column>
            <el-table-column prop="createTime" header-align="center" align="center" show-overflow-tooltip label="创建时间">
            </el-table-column>

        </ec-table>

        <!-- 表格表尾 -->
        <template slot="footer">
            <ec-pagination :page="page" @size-change="handleSizeChange" @current-change="handleCurrentChange">
            </ec-pagination>
        </template>

        <!-- 选择模板 -->
        <generate-table v-if="generateTableVisible" ref="generateTable" @callback="setTemplateList"></generate-table>
    </d2-container>
</template>

<script>
    import * as generateService from '@/api/development/generate'
    import * as tableDataService from '@/api/bdms/tabledata'
    import * as tableInfoService from '@/api/bdms/tableinfo'
    import * as centerService from '@/api/development/center'
    import GenerateTable from './generate-table';
    import {
        mapState,
        mapGetters
    } from 'vuex'
    export default {
        data() {
            return {
                dbTypeOptions: [{
                        label: 'mysql',
                        value: 'mysql'
                    },
                    {
                        label: 'oracle',
                        value: 'oracle'
                    },
                    {
                        label: 'sqlserver',
                        value: 'sqlserver'
                    },
                    {
                        label: 'postgresql',
                        value: 'postgresql'
                    },
                ],
                dbNameOptions: [{
                        label: 'ec_chat',
                        value: 'ec_chat'
                    },
                    {
                        label: 'ec_transcation',
                        value: 'ec_transcation'
                    },
                    {
                        label: 'ec-nacos',
                        value: 'ec-nacos'
                    },
                    {
                        label: 'ec_system',
                        value: 'ec_system'
                    },
                    {
                        label: 'ec_oauth2',
                        value: 'ec_oauth2'
                    },
                    {
                        label: 'ec_log',
                        value: 'ec_log'
                    },
                    {
                        label: 'ec_file',
                        value: 'ec_file'
                    },
                    {
                        label: 'ec_report',
                        value: 'ec_report'
                    },
                    {
                        label: 'ec_development',
                        value: 'ec_development'
                    },
                ],
                searchForm: {
                    dbType: 'mysql',
                    dbName: '',
                    tableName: '',
                },
                configForm: {
                    package: 'com.tjw.ec',
                    moduleName: '',
                    author: '',
                    email: '',
                    tablePrefix: '',
                },
                page: {
                    page: 1,
                    limit: 10,
                    total: 0
                },
                showHeader: true,
                tabledata: [],
                loading: false,
                addOrUpdateVisible: false,
                multipleSelection: [],
                generateTableVisible: false,
                templateList: [],
                centerData: '',
                centerDatas: [],
            }
        },
        components: {
            GenerateTable
        },
        computed: {
            ...mapGetters('d2admin/user', [
                'userinfo'
            ])
        },
        mounted() {
            this.init();
            this.getDevCenter();
            this.getDataTable()
        },
        methods: {
            // 设置参数
            init() {
                this.configForm = {
                    package: 'com.tjw.ec',
                    moduleName: '',
                    author: this.userinfo.username,
                    email: this.userinfo.email,
                    tablePrefix: '',
                }
            },
            // 获取开发中心
            getDevCenter() {
                centerService.getCenterList({}).then(data => {
                    this.centerDatas = data
                })
            },
            // 数据切换
            dataChange(obj) {
                this.searchForm.dbName = this.centerData.databaseName
                this.configForm.moduleName = this.centerData.moduleCode
            },
            // 获取数据列表
            getDataTable() {
                this.$refs['searchForm'].validate((valid) => {
                    if (valid) {
                        this.loading = true
                        let query = {
                            page: this.page.page,
                            limit: this.page.limit,
                            dbName: this.searchForm.dbName,
                            dbType: this.searchForm.dbType,
                            tableName: this.searchForm.tableName,
                        };
                        generateService.getList(query).then(data => {
                            this.tabledata = data.list;
                            this.page.total = data.totalCount;
                            this.loading = false;
                        }).catch((res) => {
                            this.loading = false;
                        });
                    }
                })
            },
            // 选择模板
            selectTemplate() {
                this.generateTableVisible = true
                this.$nextTick(() => {
                    this.$refs.generateTable.init()
                })
            },
            // 回调模板列表
            setTemplateList(templates) {
                this.templateList = templates
            },
            // 删除模板
            handleClose(tag) {
                const pkTemplate = tag.pkTemplate;
                if (this.templateList && this.templateList.length > 0) {
                    this.templateList.forEach((item, index) => {
                        if (item.pkTemplate === pkTemplate) {
                            this.templateList.splice(index, 1)
                        }
                    })
                }
            },
            generateCode() {

                if (this.templateList && this.templateList.length > 0) {

                    this.$refs['configForm'].validate((valid) => {
                        if (valid) {

                            var tableNames = this.multipleSelection.map(item => {
                                return item.tableName
                            })

                            if (tableNames.length > 0) {
                                let params = {
                                    tables: tableNames.join(","),
                                    package: this.configForm.package,
                                    moduleName: this.configForm.moduleName,
                                    author: this.configForm.author,
                                    email: this.configForm.email,
                                    tablePrefix: this.configForm.tablePrefix,
                                    pkTemplates: this.templateList.map(item => {
                                        return item.pkTemplate
                                    }).join(","),
                                    dbName: this.searchForm.dbName,
                                    dbType: this.searchForm.dbType,
                                    buildMode: 'online'
                                }
                                generateService.generatorCode(params).then(data => {
                                    let fileName = tableNames[0]
                                    if (tableNames.length > 1) {
                                        fileName = fileName + "等"
                                    }
                                    fileName = fileName + ".zip"
                                    this.downloadFile(data, fileName)
                                })
                            } else {
                                this.$message.warning("请选择要生成的数据表！")
                            }

                        }
                    })
                } else {
                    this.$message.warning("请选择模板")
                }

            },
            generateMateData() {
                var tableNames = this.multipleSelection.map(item => {
                    return item.tableName
                })

                if (tableNames.length > 0) {
                    this.$confirm("确认生成元数据？", "确认信息", {
                        distinguishCancelAndClose: true,
                        confirmButtonText: "确定",
                        cancelButtonText: "取消"
                    }).then(() => {
                        let params = {
                            tableName: tableNames.join(","),
                            dbName: this.searchForm.dbName,
                            dbType: this.searchForm.dbType,
                        }
                        tableInfoService.addtableinfo(params).then(data => {
                            this.$message.success("生成成功！")
                        })
                    });
                } else {
                    this.$message.warning("请选择要生成的数据表！")
                }

            },
            // 下载文件
            downloadFile(data, fileName) {
                if (!data) {
                    return
                }
                let url = window.URL.createObjectURL(new Blob([data], {
                    type: 'application/octet-stream'
                }))
                let link = document.createElement('a')
                link.style.display = 'none'
                link.href = url
                link.setAttribute('download', fileName)

                document.body.appendChild(link)
                link.click()
            },
            //切换页数
            handleSizeChange(val) {
                this.page.limit = val;
                this.getDataTable();
            },
            // 翻页
            handleCurrentChange(val) {
                this.page.page = val;
                this.getDataTable();
            },
            // 切换显示搜索表头
            changeHeader() {
                this.showHeader = !this.showHeader
            },
            // 重置搜索表单
            handleFormReset() {
                this.$refs.searchForm.resetFields()
            },
            handleSelectionChange(val) {
                this.multipleSelection = val;
            },
        }
    }
</script>